package com.fsquare.inventory.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.broadleafcommerce.core.catalog.domain.Sku;
import org.springframework.stereotype.Repository;

import com.fsquare.inventory.domain.SkuMovement;

@Repository("skuMovementDao")
public class SkuMovementDaoImpl implements SkuMovementDao {
	
	@PersistenceContext(unitName = "blPU")
    protected EntityManager em;

    @Resource(name = "blEntityConfiguration")
    protected EntityConfiguration entityConfiguration;
	
    @SuppressWarnings("unchecked")
	@Override
	public List<SkuMovement> getSkuMovements(Sku sku) {
    	final Query query = em.createNamedQuery("SKU_MOVEMENTS");
        query.setParameter("skuId", sku.getId());
        return (List<SkuMovement>)query.getResultList();
	}
    
    @Override
	public List<SkuMovement> getSkuMovements(Long skuId) {
    	final Query query = em.createNamedQuery("SKU_MOVEMENTS");
        query.setParameter("skuId", skuId);
        @SuppressWarnings("unchecked")
		List<SkuMovement> resultList = (List<SkuMovement>)query.getResultList();
		return resultList;
	}
    
    @Override
    public SkuMovement save(SkuMovement skuMovement) {

//    	SkuMovement response = null;

    	if(skuMovement.getId() == null)
    		em.persist(skuMovement);
        else
        	return em.merge(skuMovement);
    	
    	em.flush();
    	
        return skuMovement;
    }
    
    @Override
    public SkuMovement createSkuMovement() {
    	SkuMovement skuMovement = (SkuMovement) entityConfiguration.createEntityInstance(SkuMovement.class.getName());
        return skuMovement;
    }
    
}
